package com.kordar.admin.modular.sys.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kordar.admin.modular.sys.entity.AdminEntity;
import com.kordar.admin.modular.sys.entity.TenantEntity;
import com.kordar.admin.modular.sys.enums.AdminType;
import com.kordar.admin.modular.sys.mapper.TenantMapper;
import com.kordar.rbac.AuthManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, TenantEntity> implements TenantService {

    TenantMapper tenantMapper;

    final
    AuthManager authManager;

    public TenantServiceImpl(AuthManager authManager) {
        this.authManager = authManager;
    }

    @Autowired
    public void setMenuMapper(TenantMapper tenantMapper) {
        this.tenantMapper = tenantMapper;
    }

    @Override
    public boolean hasExists(String field, Object object) {
        QueryWrapper<TenantEntity> query = new QueryWrapper<>();
        query.eq(field, object);
        return getOne(query, false) != null;
    }

    @Override
    public TenantEntity findOneByCode(String code) {
        return getOne(new QueryWrapper<TenantEntity>().eq("code", code), false);
    }

    @DS("#kordardb")
    @Override
    public boolean initSystem(TenantEntity entity) {
        AdminEntity admin = new AdminEntity();
        admin.setType(AdminType.TYPE_SUPER.getCode());
        admin.setUsername(entity.getUsername());
        admin.generatePassword(entity.getPassword());
        admin.generateAvatar();
        admin.setCreateTime(new Date());
        admin.setUpdateTime(new Date());
        tenantMapper.initTable(entity.getCode(), admin);
        return true;
    }

    @DS("#kordardb")
    @Override
    public boolean destroySystem(TenantEntity entity) {
        tenantMapper.dropTable(entity.getCode());
        return true;
    }

    @Override
    public boolean updateTenant(String code, int status) {
        tenantMapper.update(null,
                new UpdateWrapper<TenantEntity>().eq("code", code).set("init", status)
        );
        return true;
    }


}
